import Cookie from 'js-cookie'
import User from '@/api/user'
import Token from '@/utils/token'
import router from '@/router'
import Layout from '@/layout'
import  jwt  from  'jsonwebtoken'
import Message from '@/utils/message'
import { TokenType } from '@/utils/enum'
import Data from '@/api/data'
const state = {
  name: Cookie.get('name'),
  avatar: Cookie.get('avatar'),
  routes: [],
  roleCodes: [],
  labour: {},
  company: {},
  staff: {},
  username: ''
}

// 取消权限 注释
const mutations = {
  SET_NAME: (state, name) => {
    state.name = name
  },
  SET_AVATAR: (state, avatar) => {
    state.avatar = avatar
  },
  SET_ROUTES: (state, permissions) => {
    const routes = JSON.parse(JSON.stringify(router.options.routes));
    //根据权限过滤路由
    state.routes = filterAsyncRoutes(routes, permissions)
    state.routes.push({path: '*', redirect: '/404', hidden: true})
  },
}

const actions = {
  // user login
  async login(context, userInfo) {
    const {username, password} = userInfo
    const data = await User.login({username: username.trim(), password: password})
    if (data) {
      Token.set(data)
      Cookie.set('firstLogin', 'true')
      return true
    }
  },
  async vworkLogin(context, code) {
    const data = await User.vworkLogin(code)
    if (data) {
      Token.set(data)
      Cookie.set('firstLogin', 'true')
      return true
    }
  },

  // get user info
  async getInfo({commit}) {
    var promises = sessionStorage.getItem("promises");
    if(promises && promises.split(",").length > 0) {
      var list = promises.split(",");
      console.log("存在缓存权限", list)
      var userName = sessionStorage.getItem("userName");
      commit('SET_NAME', userName)
      commit('SET_ROUTES', list)
      return true
    }
    let jwt = require('jsonwebtoken');
    console.log("getInfo",TokenType)
    let token = jwt.decode(Cookie.get(TokenType.USER_TOKEN)?Cookie.get(TokenType.USER_TOKEN):Cookie.get(TokenType.USER_REFRESHTOKEN))
		var res = await Data.get("/user/aid/" + token.user_info.aid);
    var promises;
    if(res && res.id) {
      sessionStorage.setItem("userId", res.id);
      sessionStorage.setItem("userName", res.name);
			sessionStorage.setItem("name", res.mainDeptName + "-" + res.name);
      commit('SET_NAME', res.name)
      var res2 = await Data.get("/user/ruleCodes/" + res.id);
      if(res2) {
        promises = res2
        sessionStorage.setItem("promises", promises);
        console.log("promises", promises)
        commit('SET_ROUTES', promises)
        return true
      }
    } else {
      Message({
        type: "error",
        title: "用户未同步",
        message: "您的账号未同步，如有需要请联系管理员",
        duration: 0,
      })
      Message({type: "error", message: "",duration: 0})
    }
    return false
  },

  // 刷新用户token
  async reFresh() {
    const data = await User.refresh()
    if (data) {
      Token.set(data)
      return true
    }
  },
  fedLogOut() {
    console.log("fedLogOut......");
    // var isComWx = /wxwork/i.test(window.navigator.userAgent);
    // console.log("是否企业微信..." + isComWx);
    Token.remove()
    Cookie.remove('name')
    Cookie.set('redirect', 'true')
		router.replace(`/login?type=fedLogOut`)

  },
  logOut() {
    console.log("logOut......");
    Token.remove()
    Cookie.remove('name')
    Cookie.set('redirect', 'true')
    router.replace(`/login?type=logOut`)
  }
}

// eslint-disable-next-line
function _addRoutes(menus) {
  const routes = []
  for (const item of menus) {
    const obj = {}
    obj.children = []
    obj.path = item.url
    obj.component = Layout
    if (item.subMenus.length > 0) { // 有子菜单
      obj.alwaysShow = true
      obj.redirect = 'noRedirect'
      // obj.name = item.name
      obj.meta = {
        title: item.name
      }
      obj.meta.icon = item.name
      for (const childrenItem of item.subMenus) {
        const childrenObj = {}
        childrenObj.path = childrenItem.url
        if (item.url === '/query') {
          // childrenObj.component = () => import(`@/views${childrenItem.url}${childrenItem.url}`)   ESLink 报错 换require方式
          childrenObj.component = resolve => require([`@/views${childrenItem.url}${childrenItem.url}`], resolve)
        } else {
          // childrenObj.component = () => import(`@/views${childrenItem.url}`)
          childrenObj.component = resolve => require([`@/views${childrenItem.url}`], resolve)
        }
        childrenObj.path = childrenItem.url
        childrenObj.name = childrenItem.name
        childrenObj.meta = {
          title: childrenItem.name
        }
        obj.children.unshift(childrenObj)
      }
    } else { // 没有子菜单
      obj.redirect = 'noRedirect'
      const childrenObj = {}
      childrenObj.name = item.name
      childrenObj.path = item.url
      childrenObj.meta = {
        title: item.name
      }
      // childrenObj.component = () => import(`@/views${item.url}${item.url}`)
      childrenObj.component = resolve => require([`@/views${item.url}${item.url}`], resolve)
      childrenObj.meta.icon = item.name
      obj.children.push(childrenObj)
    }
    routes.push(obj)
  }
  return routes
}

//判断当前角色是否有访问权限
function hasPermission(promises, route) {
  if (route.meta && route.meta.promises) {
    return promises.some(promise => route.meta.promises.includes(promise))
  } else {
    return true
  }
}
// 递归过滤异步路由表，筛选角色权限路由
function filterAsyncRoutes(routes, promises) {
  const res = [];
  routes.forEach(route => {
    const tmp = { ...route }
    if (hasPermission(promises, tmp)) {
      if (tmp.children) {
        tmp.children = filterAsyncRoutes(tmp.children, promises)
      }
      res.push(tmp)
    }
  })

  return res
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
